<template>
  <van-row class="orderingList">
    <div class="title">
      <van-dropdown-menu @click="dropdownChange" active-color="#08D781">
        <van-dropdown-item
          v-model="state.titlActive"
          :options="state.titleList"
        />
        <van-icon
          @click.stop="backBtn"
          name="arrow-left"
          style="position: absolute; top: 16px; left: 16px; font-size: 18px"
        />
      </van-dropdown-menu>
    </div>
    <div style="width: 100%; padding: 55px 16px 0 16px">
      <van-index-bar
        @change="indexBarChange"
        :index-list="state.indexList"
        ref="indexBarRef"
      >
        <div v-for="item in state.titleList" :key="item">
          <div v-if="!state.mealTypeList.includes(item.id)">
            <van-index-anchor :index="item.name"></van-index-anchor>
            <div style="margin-top: 10px">
              <div
                v-for="meal in item.patientNutritionFoods"
                :key="meal.id"
                @click="mealEvent(item, meal)"
                class="meal-list"
              >
                <van-row
                  v-if="!state.gearopenList.includes(meal.gearopenId)"
                  align="center"
                  :class="{ 'active-text': meal.quantity > 0 }"
                >
                  <van-col span="12" align="left">
                    <van-row align="center">
                      <SvgIcon
                        color="red"
                        width="18"
                        height="18"
                        name="delete"
                        v-if="meal.quantity > 0"
                        @click.stop="deleteEvent(meal)"
                      ></SvgIcon>
                      <span style="font-size: 14px; vertical-align: middle">
                        {{ meal.name }}</span
                      >
                    </van-row>
                  </van-col>
                  <van-col span="8">
                    <div style="border-bottom: 1px dashed"></div>
                  </van-col>
                  <van-col span="4" class="price" align="right">
                    <span>{{ meal.price }}</span>
                    <van-badge
                      v-if="meal.quantity > 0"
                      :content="meal.quantity"
                    >
                      <div class="child" />
                    </van-badge>
                  </van-col>
                </van-row>
              </div>
            </div>
          </div>
        </div>
      </van-index-bar>
    </div>
    <div
      @click="subMitEvent"
      v-if="state.selectGoodsList.length > 0"
      class="van-submit-bar"
    >
      <div class="amount">
        <div>
          <SvgIcon
            style="vertical-align: middle"
            name="bowl"
            color="#999"
          ></SvgIcon>
          <span> x </span>
          <span>{{ state.goodsNumber }}</span>
        </div>
        <div style="margin-left: 20px">
          <span>￥</span>
          <span>{{ state.totalAmount }}</span>
        </div>
      </div>
      <div @click.stop="placeOrder" class="button">
        <span>下单</span>
      </div>
    </div>
    <van-popup
      class="popup"
      v-model:show="state.orderShow"
      position="bottom"
      :style="{ height: '90%' }"
    >
      <van-icon
        @click="state.orderShow = false"
        name="play"
        class="down-icon"
      />

      <div>
        <van-empty
          v-if="state.selectGoodsList.length <= 0"
          image="https://fastly.jsdelivr.net/npm/@vant/assets/custom-empty-image.png"
          image-size="80"
          description="购物车内没有餐品"
          style="margin-top: 60%"
        />
        <div v-else>
          <div class="order-top-bar">
            <div class="amount">
              <div>
                <SvgIcon
                  style="vertical-align: middle"
                  name="bowl"
                  color="#999"
                ></SvgIcon>
                <span> x </span>
                <span>{{ state.goodsNumber }}</span>
              </div>
              <div style="margin-left: 20px">
                <span>￥</span>
                <span>{{ state.totalAmount }}</span>
              </div>
            </div>
            <div class="button">
              <span
                v-if="state.editTextFlag == 0"
                @click="state.editTextFlag = 1"
              >
                编辑
              </span>
              <span v-if="state.editTextFlag == 1" @click="completeEvent">
                完成
              </span>
            </div>
          </div>
        </div>
        <div
          class="goods-list"
          v-for="goods in state.selectGoodsList"
          :key="goods.id"
        >
          <van-row align="center">
            <van-col align="left" span="12">
              <span style="font-size: 14px">{{ goods.name }}</span>
            </van-col>
            <van-col align="right" span="12">
              <van-row align="center">
                <van-col v-if="state.editTextFlag == 0" span="18">
                  <span style="margin-right: 40px; font-size: 14px">
                    {{ goods.quantity }}份
                  </span>
                </van-col>
                <van-col span="6" v-if="state.editTextFlag == 0">
                  <span>{{ goods.price }}</span></van-col
                >
                <van-col span="24" v-if="state.editTextFlag == 1">
                  <van-stepper :min="0" v-model="goods.quantity" />
                </van-col>
              </van-row>
            </van-col>
          </van-row>
        </div>
      </div>
      <div @click.stop="placeOrder" class="order-top-bar order-bottom-bar">
        <span>下单</span>
      </div>
    </van-popup>
  </van-row>
</template>
<script setup>
import { computed, reactive, ref } from "vue";
import { arrGoAgain, setStorage } from "@/utils/common";
import { useRoute, useRouter } from "vue-router";
import { typeAndFoodList, jumpToOrderPageFood } from "@/api/goods/goodsManage";
import { siteTitle } from "@/settings";
import { findByName } from "@/api/orderingDishes/orderingDishes";
import { getStorage } from "../../utils/common";
const indexBarRef = ref("");
const router = useRouter();
const route = useRoute();
const state = reactive({
  editTextFlag: 0,
  orderShow: false,
  selectGoodsList: [],
  totalAmount: 0,
  goodsNumber: 0,
  indexBarStr: "",
  titlActive: 0,
  indexList: [],
  titleList: [],
  reservationConfDate: route.query.reservationConfDate,
  reservationType: route.query.reservationType,
  week: route.query.week,
  mealListData: {},
  mealTypeList: [],
  gearopenList: [],
});
// 获取配置规则
const queryCofig = () => {
  findByName({ name: "OrderingConfiguration" }).then((v) => {
    state.mealListData = JSON.parse(v.data.value);
    console.log(state.mealListData);
    const { special, mealList, weekendMealList } = state.mealListData;
    // 周一到周五的规则
    if (state.week >= 1 && state.week <= 5) {
      if (mealList[state.reservationType - 1].open) {
        mealList[state.reservationType - 1].mealLimit.forEach((value) => {
          state.titleList.forEach((title, index) => {
            if (title.id == value) {
              state.titleList.splice(index, 1);
              state.indexList.splice(index, 1);
            }
          });
          state.mealTypeList.push(value);
        });
        mealList[state.reservationType - 1].mealMouth.forEach((value) => {
          state.gearopenList.push(value);
        });
      }
      state.titlActive = state.titleList[0].id;
    } else {
      if (weekendMealList[state.reservationType - 1].open) {
        weekendMealList[state.reservationType - 1].mealLimit.forEach(
          (value) => {
            state.titleList.forEach((title, index) => {
              if (title.id == value) {
                state.titleList.splice(index, 1);
                state.indexList.splice(index, 1);
              }
            });
            state.mealTypeList.push(value);
          }
        );
        weekendMealList[state.reservationType - 1].mealMouth.forEach(
          (value) => {
            state.gearopenList.push(value);
          }
        );
      }
      state.titlActive = state.titleList[0].id;
    }
    // 特殊规则
    special.list[state.reservationType - 1].mealLimit.forEach((value) => {
      if (
        state.week == special.list[state.reservationType - 1].week &&
        special.list[state.reservationType - 1].open
      ) {
        state.titleList.forEach((title, index) => {
          if (title.id == value) {
            state.gearopenList.push(value);
          }
        });
        state.mealTypeList.push(value);
      }
      state.titlActive = state.titleList[0].id;
    });

    special.list[state.reservationType - 1].mealMouth.forEach((value) => {
      if (
        state.week == special.list[state.reservationType - 1].week &&
        special.list[state.reservationType - 1].open
      ) {
        state.gearopenList.push(value);
      }
    });
  });
};
// 获取列表
const queryFoodList = () => {
  // 调用配置规则
  typeAndFoodList({}).then((v) => {
    let data = v.data;
    let resultData = data;
    // const { special, mealList, weekendMealList } = state.mealListData;
    // if (
    //   state.week >= 1 &&
    //   state.week <= 5 &&
    //   mealList[state.reservationType - 1].open
    // ) {
    //   resultData = data.filter((item) => {
    //     return !mealList[state.reservationType - 1].mealLimit.includes(item.id);
    //   });
    // } else if (
    //   (state.week == 6 || state.week == 7) &&
    //   weekendMealList[state.reservationType - 1].open
    // ) {
    //   console.log(weekendMealList[state.reservationType - 1].open);
    //   resultData = data.filter((item) => {
    //     return !weekendMealList[state.reservationType - 1].mealLimit.includes(
    //       item.id
    //     );
    //   });
    // }

    // // 特殊规则
    // special.list[state.reservationType - 1].mealLimit.forEach((value) => {
    //   if (
    //     state.week == special.list[state.reservationType - 1].week &&
    //     special.list[state.reservationType - 1].open
    //   ) {
    //     resultData = data.filter((item) => {
    //       return !special.list[state.reservationType - 1].mealLimit.includes(
    //         item.id
    //       );
    //     });
    //   }
    // });

    state.titleList = resultData;
    state.titleList.forEach((value) => {
      value.patientNutritionFoods.forEach((meal) => {
        meal.quantity = 0;
      });
      value.text = value.name;
      value.value = value.id;
      state.indexList.push(value.name);
    });
    state.titlActive = state.titleList[0].id;
    queryCofig();
  });
};
queryFoodList();
// 菜品数量计算
state.goodsNumber = computed(() => {
  let number = 0;
  console.log(state.titleList);
  state.titleList.forEach((value) => {
    value.patientNutritionFoods.forEach((meal) => {
      number += meal.quantity;
    });
  });
  return number;
});
// 菜品价格计算
state.totalAmount = computed(() => {
  let totalAmount = 0;
  state.titleList.forEach((value) => {
    value.patientNutritionFoods.forEach((meal) => {
      totalAmount += meal.quantity * meal.price;
    });
  });
  return totalAmount;
});
// 下拉change
const dropdownChange = () => {
  state.titleList.forEach((value) => {
    if (value.id == state.titlActive) {
      console.log(value);
      state.indexBarStr = value.name;
    }
  });
  indexBarRef.value.scrollTo(state.indexBarStr);
};

// 索引Change
const indexBarChange = (val) => {
  state.titleList.forEach((value, index) => {
    if (value.text == val) {
      state.titlActive = value.id;
    }
  });
};
// 点击菜品事件
const mealEvent = (classObj, meal) => {
  console.log(classObj, meal);
  meal.quantity++;
  meal.mealId = `${classObj.id}${meal.id}`;
  meal.foodId = meal.id;
  state.selectGoodsList.push(meal);
  state.selectGoodsList = arrGoAgain(state.selectGoodsList, 1);
};
// 点击删除菜品
const deleteEvent = (val) => {
  val.quantity--;
  state.selectGoodsList.forEach((goods, index) => {
    state.titleList.forEach((title) => {
      console.log(title);
      title.patientNutritionFoods.forEach((meal) => {
        if (goods.mealId == `${title.id}${meal.id}` && meal.quantity == 0) {
          state.selectGoodsList.splice(index, 1);
          console.log(state.selectGoodsList);
        }
      });
    });
  });
};
// 点击sunbmitBar事件
const subMitEvent = () => {
  state.orderShow = true;
};
// 点击完成按钮
const completeEvent = () => {
  const newArr = [];
  state.selectGoodsList.forEach((value, index) => {
    if (value.quantity > 0) {
      newArr.push(value);
    }
  });
  state.selectGoodsList = newArr;
  state.editTextFlag = 0;
};
// 返回上一页
const backBtn = () => {
  router.go(-1);
};
// 下单按钮
const placeOrder = () => {
  const qrCodeData = JSON.parse(getStorage(siteTitle + "_qrCodeData"));
  const params = {
    detailsParams: state.selectGoodsList,
    deptId: "1652255343972974592",
    reservationConfDate: state.reservationConfDate,
    reservationType: state.reservationType,
    wardCode: qrCodeData.wardCode,
    bedNo: qrCodeData.bedNo,
  };

  jumpToOrderPageFood(params).then((v) => {
    setStorage(siteTitle + "_goodsList", JSON.stringify(params));

    router.push({
      name: "payment",
      query: {
        type: 1,
        totalAmount: state.totalAmount,
      },
    });
  });
};
</script>
<style lang="scss" scoped>
.orderingList {
  padding-bottom: 56px;
  .title {
    width: 100%;
    position: fixed;
    top: 0;
    z-index: 10;
    background: #f9f9f9;
    ::v-deep .van-ellipsis {
      font-size: 14px;
    }
  }
  & * {
    box-sizing: border-box;
  }
  .van-index-bar {
    width: 100%;
    // margin-top: 48px;
  }
  ::v-deep .van-index-bar__sidebar {
    display: none;
  }
  .meal-list {
    & > .van-row {
      margin-bottom: 10px;
      padding: 10px 16px;
      border-radius: 10px;
    }
    .active-text {
      background: #08d781;
      color: #fff;
      .svg-icon {
        border-radius: 50%;
        background: #fff;
        margin-top: 2px;
        margin-right: 5px;
      }
      .price {
        span {
          vertical-align: sub;
        }
        ::v-deep .van-badge__wrapper {
          display: inline-block;
          vertical-align: middle;
          margin-left: 5px;
          .van-badge {
            position: inherit;
            transform: none;
            background: #fff;
            color: #08d781;
          }
        }
      }
    }
    .delete-icon {
      vertical-align: middle;
    }
  }
  .van-submit-bar,
  .order-top-bar {
    box-shadow: 0 2px 12px rgba(100, 101, 102, 0.12);
    padding: 16px 16px;

    & > div {
      display: inline-block;
      vertical-align: middle;
    }
    .button {
      float: right;
      span {
        font-size: 16px;
        color: #08d781;
      }
    }
    .amount {
      & > div {
        display: inline-block;
        vertical-align: middle;
        span {
          font-size: 14px;
        }
      }
      float: left;
    }
  }
  .order-top-bar {
    overflow: hidden;
    box-shadow: none;
    border-bottom: 1px solid #e7e7e7;
    padding: 10px 0;
  }
  .order-bottom-bar {
    text-align: center;
    width: 100%;
    position: fixed;
    bottom: 0;
    border: none;
    margin-left: -16px;
    box-shadow: 0 2px 12px rgba(100, 101, 102, 0.12);
    span {
      font-size: 16px;
      color: #08d781;
    }
  }
  .van-overlay {
    background: #000;
    opacity: 0.9;
  }
  .popup {
    padding: 10px 16px;
    & * {
      box-sizing: border-box;
    }
    .down-icon {
      color: #999;
      font-size: 20px;
      transform: rotate(90deg);
      // margin-top: 5px;
    }
    .goods-list {
      padding: 16px 0;
    }
  }
}
</style>
